#import "CTPBaseUrlFetcher.h"

@implementation CTPBaseUrlFetcher


- (NSMutableURLRequest*)makeRequest:(NSString*)url {
	NSString *encodedUrl = (NSString*)CFURLCreateStringByAddingPercentEscapes(
																			  NULL, (CFStringRef)url, NULL, NULL, kCFStringEncodingUTF8);
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:encodedUrl]];
	[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
	[request setTimeoutInterval:TIMEOUT_SEC];
	[request setHTTPShouldHandleCookies:FALSE];
	[encodedUrl release];
	return request;
}

- (void)prepareWithRequest:(NSMutableURLRequest*)request {
	// do nothing (for OAuthHttpClient)
}

- (void)requestGET:(NSString*)url{
	[self reset];
	NSMutableURLRequest *request = [self makeRequest:url];
	[self prepareWithRequest:request];
	connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}

-(void)requestSucceeded {
	// implement by subclass
}

-(void)requestFailed:(NSError*)error {
	// implement by subclass
}

-(void)cancel {
	[connection cancel];
	[self reset];
	[self requestFailed:nil];
}

-(void)reset {
	[recievedData release];
	recievedData = [[NSMutableData alloc] init];
	[connection release];
	connection = nil;
	[rate_limit_reset release];
	rate_limit_reset = nil;
	
	statusCode = 0;	
	contentTypeIsXml = NO;
	
	rate_limit = 0;
	rate_limit_remaining = 0;
}

-(void)dealloc{
	[connection release];
	[recievedData release];
	[rate_limit_reset release];
	[super dealloc];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[recievedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[recievedData appendData:data];
	
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	//    NSLog(@"connectionDidFinishLoading");
	[self requestSucceeded];
	[self reset];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*) error {
	//    NSLog(@"didFailWithError");
	[self requestFailed:error];
	[self reset];
}

@synthesize recievedData, statusCode;

@end